from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from .. import models, schemas
from datetime import datetime
from typing import List, Optional
from sqlalchemy import or_, and_

def get_or_create_friend_chat_session(db: Session, user1_id: str, user2_id: str) -> models.FriendChatSession:
    """获取或创建好友聊天会话"""
    # 查找现有会话
    session = db.query(models.FriendChatSession).filter(
        or_(
            and_(
                models.FriendChatSession.user1_id == user1_id,
                models.FriendChatSession.user2_id == user2_id
            ),
            and_(
                models.FriendChatSession.user1_id == user2_id,
                models.FriendChatSession.user2_id == user1_id
            )
        )
    ).first()
    
    if not session:
        # 创建新会话
        session = models.FriendChatSession(
            user1_id=min(user1_id, user2_id),  # 保证小ID在前，方便查询
            user2_id=max(user1_id, user2_id)
        )
        db.add(session)
        db.commit()
        db.refresh(session)
    
    return session

def get_or_create_avatar_chat_session(db: Session, user_id: str, avatar_id: str) -> models.AvatarChatSession:
    """获取或创建化身聊天会话"""
    session = db.query(models.AvatarChatSession).filter(
        models.AvatarChatSession.user_id == user_id,
        models.AvatarChatSession.avatar_id == avatar_id
    ).first()
    
    if not session:
        session = models.AvatarChatSession(
            user_id=user_id,
            avatar_id=avatar_id
        )
        db.add(session)
        db.commit()
        db.refresh(session)
    
    return session

def create_friend_message(db: Session, message: schemas.FriendChatMessageCreate, from_user_id: str) -> models.FriendChatMessage:
    """创建好友聊天消息"""
    # 检查是否是好友
    from .friend import check_if_friends
    if not check_if_friends(db, from_user_id, message.to_user_id):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只能给好友发送消息"
        )
    
    # 获取或创建会话
    session = get_or_create_friend_chat_session(db, from_user_id, message.to_user_id)
    
    # 创建消息
    db_message = models.FriendChatMessage(
        content=message.content,
        from_user_id=from_user_id,
        to_user_id=message.to_user_id,
        is_read=False
    )
    db.add(db_message)
    
    # 更新未读消息计数
    if session.user1_id == message.to_user_id:
        session.user1_unread_count += 1
    else:
        session.user2_unread_count += 1
    
    db.commit()
    db.refresh(db_message)
    return db_message

def create_avatar_message(
    db: Session, 
    message: schemas.AvatarChatMessageCreate, 
    user_id: str,
    is_from_user: bool = True
) -> models.AvatarChatMessage:
    """创建化身聊天消息"""
    # 获取或创建会话
    get_or_create_avatar_chat_session(db, user_id, message.avatar_id)
    
    db_message = models.AvatarChatMessage(
        content=message.content,
        user_id=user_id,
        avatar_id=message.avatar_id,
        is_from_user=is_from_user
    )
    db.add(db_message)
    db.commit()
    db.refresh(db_message)
    return db_message

def get_friend_chat_history(
    db: Session,
    user_id: str,
    friend_id: str,
    skip: int = 0,
    limit: int = 50
) -> List[models.FriendChatMessage]:
    """获取好友聊天历史"""
    return db.query(models.FriendChatMessage).filter(
        or_(
            and_(
                models.FriendChatMessage.from_user_id == user_id,
                models.FriendChatMessage.to_user_id == friend_id
            ),
            and_(
                models.FriendChatMessage.from_user_id == friend_id,
                models.FriendChatMessage.to_user_id == user_id
            )
        )
    ).order_by(
        models.FriendChatMessage.created_at.desc()
    ).offset(skip).limit(limit).all()

def get_avatar_chat_history(
    db: Session,
    user_id: str,
    avatar_id: str,
    skip: int = 0,
    limit: int = 50
) -> List[models.AvatarChatMessage]:
    """获取化身聊天历史"""
    return db.query(models.AvatarChatMessage).filter(
        models.AvatarChatMessage.user_id == user_id,
        models.AvatarChatMessage.avatar_id == avatar_id
    ).order_by(
        models.AvatarChatMessage.created_at.desc()
    ).offset(skip).limit(limit).all()

def get_user_chat_sessions(db: Session, user_id: str) -> List[models.ChatSession]:
    """获取用户的所有聊天会话"""
    friend_sessions = db.query(models.FriendChatSession).filter(
        or_(
            models.FriendChatSession.user1_id == user_id,
            models.FriendChatSession.user2_id == user_id
        )
    ).all()
    
    avatar_sessions = db.query(models.AvatarChatSession).filter(
        models.AvatarChatSession.user_id == user_id
    ).all()
    
    return friend_sessions + avatar_sessions

def mark_messages_as_read(db: Session, user_id: str, friend_id: str):
    """将来自某个好友的消息标记为已读"""
    # 更新消息状态
    db.query(models.FriendChatMessage).filter(
        models.FriendChatMessage.to_user_id == user_id,
        models.FriendChatMessage.from_user_id == friend_id,
        models.FriendChatMessage.is_read == False
    ).update({"is_read": True})
    
    # 重置未读计数
    session = get_or_create_friend_chat_session(db, user_id, friend_id)
    if session.user1_id == user_id:
        session.user1_unread_count = 0
    else:
        session.user2_unread_count = 0
    
    db.commit()

def get_unread_messages(db: Session, user_id: str) -> List[models.FriendChatMessage]:
    """获取用户的所有未读消息"""
    return db.query(models.FriendChatMessage).filter(
        models.FriendChatMessage.to_user_id == user_id,
        models.FriendChatMessage.is_read == False
    ).order_by(
        models.FriendChatMessage.created_at.asc()
    ).all()

def get_unread_count(db: Session, user_id: str, friend_id: str) -> int:
    """获取来自特定好友的未读消息数量"""
    session = get_or_create_friend_chat_session(db, user_id, friend_id)
    if session.user1_id == user_id:
        return session.user1_unread_count
    return session.user2_unread_count

def create_avatar_chat_session(db: Session, user_id: str, avatar_id: str) -> models.AvatarChatSession:
    """创建新的化身聊天会话"""
    session = models.AvatarChatSession(
        user_id=user_id,
        avatar_id=avatar_id
    )
    db.add(session)
    db.commit()
    db.refresh(session)
    return session

def get_latest_avatar_chat_session(db: Session, user_id: str, avatar_id: str) -> models.AvatarChatSession:
    """获取最新的聊天会话"""
    return db.query(models.AvatarChatSession).filter(
        models.AvatarChatSession.user_id == user_id,
        models.AvatarChatSession.avatar_id == avatar_id
    ).order_by(models.AvatarChatSession.created_at.desc()).first() 